import * as XLSX from 'xlsx'
import {
  Document, Packer, Paragraph, TextRun, AlignmentType
} from 'docx'
import { saveAs } from 'file-saver'

const typeMap = {
  0: '一、选择题',
  1: '二、多选题',
  2: '三、填空题',
  3: '四、判断题',
  4: '五、简答题'
}

function formatOptions(optionStr = '') {
  const options = optionStr.split(',')
  return options.map((opt, i) => `${String.fromCharCode(65 + i)}. ${opt}`).join('  ')
}

function groupQuestions(questions = []) {
  const grouped = {}
  questions.forEach(q => {
    const type = q.question?.type
    if (!grouped[type]) grouped[type] = []
    grouped[type].push(q)
  })
  return grouped
}

function exportPaperToWordV2(questions = [], paperInfo = {}, withAnswer = true) {
  const docChildren = []
  const title = withAnswer ? '（含答案）' : '（不含答案）';

  // 标题
  docChildren.push(
    new Paragraph({
      children: [
        new TextRun({ text: (paperInfo.paperName || '测试试卷')+title, bold: true, size: 36 })
      ],
      alignment: AlignmentType.CENTER,
      spacing: { after: 300 }
    })
  )

  // 出卷人 + 考试时间 + 总分（由题目计算）
  const totalScore = questions.reduce((sum, q) => sum + (q.score || 0), 0)
  const paperMeta = `出卷人：${paperInfo.creator || '管理员'}    考试时间：${paperInfo.duration || '60'}分钟    试卷总分：${totalScore}分`

  docChildren.push(
    new Paragraph({
      children: [new TextRun({ text: paperMeta, size: 24 })],
      alignment: AlignmentType.CENTER,
      spacing: { after: 400 }
    })
  )

  // 题型分组
  const grouped = groupQuestions(questions)

  Object.entries(grouped).forEach(([type, list]) => {
    const typeTitle = typeMap[type] || `类型${type}`
    const typeScore = list.reduce((sum, q) => sum + (q.score || 0), 0)

    docChildren.push(
      new Paragraph({
        children: [new TextRun({ text: `${typeTitle}，共${list.length}题（共${typeScore}分）`, bold: true, size: 28 })],
        spacing: { before: 200, after: 200 }
      })
    )

    list.forEach((item, index) => {
      const q = item.question || {}
      const order = index + 1

      // 题干
      docChildren.push(
        new Paragraph({
          children: [new TextRun({ text: `${order}、${q.content || ''}`, size: 24 })],
          spacing: { after: 100 }
        })
      )

      // 选项（若有）
      if (q.options) {
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: formatOptions(q.options), size: 24 })],
            spacing: { after: 100 }
          })
        )
      }

      // 答案（可选）
      if (withAnswer) {
        const ansLabel = type == 4 ? '参考答案' : '答案'
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: `${ansLabel}：${q.correctAnswer || '略'}`, size: 22 })],
            spacing: { after: 200 }
          })
        )
      }
    })
  })

  const doc = new Document({
    sections: [{ children: docChildren }]
  })

  const filename = `${(paperInfo.paperName || '试卷')+title}.docx`
  Packer.toBlob(doc).then(blob => {
    saveAs(blob, filename)
  })
}

function exportToExcel(data, filename = '数据.xlsx') {
  const worksheet = XLSX.utils.json_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
  saveAs(blob, filename)
}

/**
 * 导出试卷
 * @param {string} encryptedStr - 加密后的试卷字符串
 * @param {string} filename - 文件名，默认为 '试卷.paper'
 */
function exportToPaper(encryptedStr, filename = '试卷.paper') {
  const blob = new Blob([encryptedStr], { type: 'text/plain;charset=utf-8' })
  saveAs(blob, filename+".paper")
}

export default {
  exportToExcel,
  exportPaperToWordV2,
  exportToPaper
}